package com.xinchuang.config;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.xinchuang.role.entity.SystemHeader;
import com.xinchuang.utils.MyUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * TODO
 *
 * @author zkwczx
 * @version 1.0
 * @date 2023/10/13 14:53
 */
public class RequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = request.getRequestURI();
        System.out.println("Request URI: " + requestUrl);
        boolean filter = false;
        switch (requestUrl) {
            case "/recordAndStatisticMod/tryOutRecordList":
            case "/recordAndStatisticMod/tryOutColsedQuestion":
                filter = verifyUrl(request, "QueryTrialMoldRecordApprovalForm");//查询试模记录审批表
                break;
            case "/recordAndStatisticMod/addTryOutRecord":
            case "/recordAndStatisticMod/addTryOutColsedQuestion":
                filter = verifyUrl(request, "EditTrialMoldRecordApprovalForm");//编辑试模记录审批表
                break;
            case "/recordAndStatisticMod/postTryOutToCheck":
                filter = verifyUrl(request, "SubmitTrialMoldRecordApprovalForm");//提交试模记录审批表
                break;
            case "/recordAndStatisticMod/exportTryOutRecord":
                filter = verifyUrl(request, "ImportTrialMoldRecordApprovalForm");//导入试模记录审批表
                break;
            case "/noteMod/addNote":
                filter = verifyUrl(request, "AddTestNotice");//新增试模通知单
                break;
            case "/tryOutPlanMod/addTryOutPlan":
                filter = verifyUrl(request, "AddTestPlan");//新增试模计划
                break;
            case "/tryOutMod/addTryOutReport":
                filter = verifyUrl(request, "AddTestReport", "UpdateTestReport");//新增试模报告 编辑试模报告
                break;
            case "/noteMod/applyToTryOut":
                filter = verifyUrl(request, "ExamineTestNotice");//试模通知单申请批准
                break;
            case "/tryOutPlanMod/changeTryOutPlan":
                filter = verifyUrl(request, "SubmitTestPlan");//提交试模计划
                break;
            case "/tryOutPlanMod/editTryOutPlan":
                filter = verifyUrl(request, "UpdateTestPlan");//编辑试模计划
                break;
            case "/stasticsMod/saveTryOutCountStastics":
                filter = verifyUrl(request, "UpdateTestCount");//编辑保存试模次数统计
                break;
            case "/stasticsMod/saveTryOutRecordList":
                filter = verifyUrl(request, "UpdateTestData");//编辑保存试模数据记录
                break;
            case "/tryOutMod/addTryOutRecord":
                filter = verifyUrl(request, "UpdateTestTime");//编辑试模记录时间
                break;
            case "/noteMod/deleteNote":
                filter = verifyUrl(request, "DeleteTestNotice");//删除试模通知单
                break;
            case "/tryOutPlanMod/deleteTryOutPlan":
                filter = verifyUrl(request, "DeleteTestPlan");//删除试模计划
                break;
            case "/moldSelectionsMod/getMoldSelectionList":
            case "/moldSelectionsMod/getMoldSelectionDetail":
                filter = verifyUrl(request, "QuerySelectionTable");//查询选模表
                break;
            case "/quotationMod/getInnerQuotation":
                filter = verifyUrl(request, "QueryTargetPriceTable");//查询目标价格表
                break;
            case "/quotationMod/getNormalOutQuotation":
                filter = verifyUrl(request, "QueryInternalExternalProjectQuotationTable");//查询内部对外项目报价表
                break;
            case "/quotationMod/getDFOutQuotation":
                filter = verifyUrl(request, "QueryDongfengMoldQuotationList");//查询东风模具报价清单
                break;
            case "/quotationMod/getJLOutQuotation":
                filter = verifyUrl(request, "QueryGeelyMoldPriceDetails");//查询吉利模具价格明细
                break;
            case "/quotationMod/getQROutQuotation":
                filter = verifyUrl(request, "QueryCheryMoldQuotationElectronicFile");//查询奇瑞模具报价单电子档
                break;
            case "/quotationMod/getBYDOutQuotation":
                filter = verifyUrl(request, "QueryBYDPlasticMoldQuotation");//查询BYD塑胶模具报价单
                break;
            case "/designChangeMod/getInnerDesignChangeDetail":
                filter = verifyUrl(request, "QueryProjectModificationCostTargetPriceTable");//查询项目设变费用目标价格表
                break;
            case "/designChangeMod/getOutDesignChange":
                filter = verifyUrl(request, "QueryTechnicalCenterMoldModificationPricingApprovalTable");//查询技术中心模具设变核价审批表
                break;
            case "/moldTypeMod/getMoldTypeList":
                filter = verifyUrl(request, "QueryMoldType");//查询模具类型
                break;
            case "/partMod/getPartPage":
            case "/partMod/getPartDetail":
            case "/partMod/getPartList":
                filter = verifyUrl(request, "QueryComponent");//查询零件
                break;
            case "/moldSelectionsMod/imoprtFile":
                filter = verifyUrl(request, "ImportSelectionTable");//导入选模表
                break;
            case "/moldSelectionsMod/saveMoldSelection":
            case "/moldSelectionsMod/postToCheck":
            case "/moldSelectionsMod/deleteSubTableById":
                filter = verifyUrl(request, "EditSaveSelectionTable");//编辑保存选模表
                break;
            case "/quotationMod/saveInnerQuotation":
            case "/quotationMod/deleteInnerQuotationSubTableById":
            case "/quotationMod/postInnerQuotationToCheck":
                filter = verifyUrl(request, "EditSaveTargetPriceTable");//编辑保存目标价格表
                break;
            case "/quotationMod/deleteOutQuotationSubTableById":
                filter = verifyUrl(request, "EditSaveInternalExternalProjectQuotationTable",//编辑保存内部对外项目报价表
                        "EditSaveDongfengMoldQuotationList",//编辑保存东风模具报价单
                        "EditSaveGeelyMoldPriceDetails",//编辑保存记录模具价格明细
                        "EditSaveCheryMoldQuotationElectronicFile",//编辑保存奇瑞模具报价单电子档
                        "EditSaveBYDPlasticMoldQuotation"//编辑保存BYD塑胶模具报价单
                );
                break;
            case "/quotationMod/saveNormalOutQuotation":
                filter = verifyUrl(request, "EditSaveInternalExternalProjectQuotationTable");//编辑保存内部对外项目报价表
                break;
            case "/quotationMod/saveDFOutQuotation":
                filter = verifyUrl(request, "EditSaveDongfengMoldQuotationList");//编辑保存东风模具报价清单
                break;
            case "/quotationMod/saveJLOutQuotation":
                filter = verifyUrl(request, "EditSaveGeelyMoldPriceDetails");//编辑保存吉利模具价格明细
                break;
            case "/quotationMod/saveQROutQuotation":
                filter = verifyUrl(request, "EditSaveCheryMoldQuotationElectronicFile");//编辑保存奇瑞模具报价单电子档
                break;
            case "/quotationMod/saveBYDOutQuotation":
                filter = verifyUrl(request, "EditSaveBYDPlasticMoldQuotation");//编辑保存BYD塑胶模具报价单
                break;
            case "/designChangeMod/saveInnerDesignChangeDetail":
            case "/designChangeMod/deleteInnerDesignChangeSubTableById":
            case "/designChangeMod/getProjectProducts":
                filter = verifyUrl(request, "EditSaveProjectModificationCostTargetPriceTable");//编辑保存项目设变费用目标价格表
                break;
            case "/designChangeMod/saveOutDesignChange":
            case "/designChangeMod/deleteOutDesignChangeSubTableById":
                filter = verifyUrl(request, "EditSaveTechnicalCenterMoldModificationPricingApprovalTable");//编辑保存技术中心模具设变核价审批表
                break;
            case "/moldTypeMod/saveMoldType":
            case "/moldTypeMod/getPartListByTypeId":
            case "/moldTypeMod/deleteMoldTypePart":
                filter = verifyUrl(request, "EditSaveMoldType");//编辑保存模具类型
                break;
            case "/partMod/savePart":
                filter = verifyUrl(request, "EditSaveComponent");//编辑保存零件
                break;
            case "/moldSelectionsMod/deleteMoldSelections":
                filter = verifyUrl(request, "DeleteSelectionTable");//删除选模表
                break;
            case "/moldTypeMod/deleteMoldType":
                filter = verifyUrl(request, "DeleteMoldType");//删除模具类型
                break;
            case "/partMod/deletePart":
                filter = verifyUrl(request, "DeleteComponent");//删除零件
                break;
            case "/quotationMod/exportInnerQuotation":
                filter = verifyUrl(request, "ExportTargetPriceTable");//导出目标价格表
                break;
            case "/quotationMod/exportOutQuotation":
                filter = verifyUrl(request, "ExportInternalExternalProjectQuotationTable",//导出内部对外项目报价表
                        "ExportDongfengMoldQuotationList",//导出东风模具报价清单
                        "ExportGeelyMoldPriceDetails",//导出吉利模具价格明细
                        "ExportCheryMoldQuotationElectronicFile",//导出奇瑞模具报价单电子档
                        "ExportBYDPlasticMoldQuotation");//导出BYD塑胶模具报价单
                break;
            case "/designChangeMod/exportInnerDesignChange":
                filter = verifyUrl(request, "ExportProjectModificationCostTargetPriceTable");//导出项目设变费用目标价格表
                break;
            case "/designChangeMod/exportOutDesignChange":
                filter = verifyUrl(request, "ExportTechnicalCenterMoldModificationPricingApprovalTable");//导出技术中心模具设变核价审批表
                break;
            case "/cron/cronList":
                filter = verifyUrl(request, "QueryCronTable");//查询定时列表
                break;
            case "/cron/addCron":
                filter = verifyUrl(request, "SaveCronTable");//添加定时
                break;
            case "/cron/editCron":
                filter = verifyUrl(request, "EditCronTable");//编辑定时
                break;
            case "/materialsBaseInfo/add":
                filter = verifyUrl(request, "SaveMaterialsBaseInfoTable");//添加物料基础信息列表
                break;
            case "/materialsBaseInfo/edit":
                filter = verifyUrl(request, "EditMaterialsBaseInfoTable");//编辑物料基础信息列表
                break;
            case "/materialsBaseInfo/delete":
                filter = verifyUrl(request, "DeleteMaterialsBaseInfoTable");//删除物料基础信息列表
                break;
            case "/materialsBaseInfo/list":
                filter = verifyUrl(request, "QueryMaterialsBaseInfoTable");//查询物料基础信息列表
                break;
            case "/moldManagementMod/moldList":
                filter = verifyUrl(request, "QueryMoldManagementModTable");//模具列表接口
                break;
            case "/moldManagementMod/addMold":
                filter = verifyUrl(request, "SaveMoldManagementModTable");//添加模具接口
                break;
            case "/moldManagementMod/editMold":
                filter = verifyUrl(request, "EditMoldManagementModTable");//编辑模具接口
                break;
            case "/moldManagementMod/deleteMold":
                filter = verifyUrl(request, "DeleteMoldManagementModTable");//删除模具接口
                break;
            case "/moldManagementMod/queryMoldByName":
                filter = verifyUrl(request, "QueryMoldByName");//模具查询
                break;
            case "/dictionaryMod/addDicType":
                filter = verifyUrl(request, "SaveDicType");//新增类型
                break;
            case "/dictionaryMod/editDicType":
                filter = verifyUrl(request, "EditDicType");//编辑类型
                break;
            case "/dictionaryMod/delDicType":
                filter = verifyUrl(request, "DeleteDicType");//删除类型接口
                break;
            case "/dictionaryMod/dicList":
                filter = verifyUrl(request, "QueryDicList");//字典数据列表接口
                break;
            case "/dictionaryMod/addDic":
                filter = verifyUrl(request, "SaveDic");//新增字典数据接口
                break;
            case "/dictionaryMod/editDic":
                filter = verifyUrl(request, "EditDic");//编辑字典数据接口
                break;
            case "/dictionaryMod/delDic":
                filter = verifyUrl(request, "DeleteDic");//删除字典接口
                break;
            case "/dictionaryMod/getDicDetail":
                filter = verifyUrl(request, "QueryDicDetail");//获取字典详情接口
                break;
            case "/dictionaryMod/dicTypeList":
                filter = verifyUrl(request, "QueryDicTypeList");//获取字典类型列表接口
                break;
            case "/tryoutDeviceMod/getDeviceList":
                filter = verifyUrl(request, "QueryDeviceList");//获取试模设备列表
                break;
            case "/tryoutDeviceMod/addDevice":
                filter = verifyUrl(request, "AddDevice");//添加试模设备接口
                break;
            case "/tryoutDeviceMod/saveDevice":
                filter = verifyUrl(request, "SaveDevice");//保存试模接口
                break;
            case "/tryoutDeviceMod/deleteDevice":
                filter = verifyUrl(request, "DeleteDevice");//删除试模设备接口
                break;
            case "/tryoutDeviceMod/queryDeviceByName":
                filter = verifyUrl(request, "QueryDeviceByName");//试模设备名称查询
                break;
            case "/api/synMold":
                filter = verifyUrl(request, "SynMold");//同步模具
                break;
            default:
                break;
        }
        if (filter) {
            // 返回特定内容
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            // 构造JSON字符串
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 403);
            jsonObject.put("message", "用户权限不足，无法访问");
            jsonObject.put("data", null);
            // 设置状态码为403禁止访问
            response.getWriter().write(jsonObject.toJSONString());
            response.setStatus(HttpServletResponse.SC_OK);
            // 终止请求继续处理
            return false;
        }
        return true;
    }

    private boolean verifyUrl(HttpServletRequest request, String... operation) {
        SystemHeader header = null;
        try {
            header = MyUtils.getHeader(request);
            if (ObjectUtil.isNull(header)) {
                return true;
            }
        } catch (Exception e) {
            return true;
        }
        List<String> operations = header.getOperations();
        if(Objects.nonNull(operations) && !operations.isEmpty()){
            String roleStr = operations.get(0);
            String[] roleArr = roleStr.split("%2C");
            for (String s : roleArr) {
                for (String s1 : operation) {
                    if (s.equals(s1)) {
                        switch (s1) {
                            case "ExportInternalExternalProjectQuotationTable":
                            case "EditSaveInternalExternalProjectQuotationTable":
                                if (request.getParameter("mainEnginePlantId").equals("1")) {
                                    return false;
                                }
                                break;
                            case "ExportDongfengMoldQuotationList":
                            case "EditSaveDongfengMoldQuotationList":
                                if (request.getParameter("mainEnginePlantId").equals("2")) {
                                    return false;
                                }
                                break;
                            case "ExportGeelyMoldPriceDetails":
                            case "EditSaveGeelyMoldPriceDetails":
                                if (request.getParameter("mainEnginePlantId").equals("3")) {
                                    return false;
                                }
                                break;
                            case "ExportCheryMoldQuotationElectronicFile":
                            case "EditSaveCheryMoldQuotationElectronicFile":
                                if (request.getParameter("mainEnginePlantId").equals("4")) {
                                    return false;
                                }
                                break;
                            case "ExportBYDPlasticMoldQuotation":
                            case "EditSaveBYDPlasticMoldQuotation":
                                if (request.getParameter("mainEnginePlantId").equals("5")) {
                                    return false;
                                }
                                break;
                            default:
                                return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
